import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
import isLogin from '@utils'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: '首页',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cate',
    name: '分类', // 路由懒加载
    component: () => import('@views/Cate'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/ItemLists',
    name: '商品列表',
    component: () => import('@views/ItemLists'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/Detail/:id', // 动态路由传参
    name: '商品详情',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/register', // 动态路由传参
    name: '用户注册',
    component: () => import('@views/Register'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login', // 动态路由传参
    name: '用户登录',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/contactLists', // 动态路由传参
    name: '联系人列表',
    component: () => import('@views/ContactLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactAdd', // 动态路由传参
    name: '添加联系人',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactUpdate', // 动态路由传参
    name: '编辑联系人',
    component: () => import('@views/ContactUpdate'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/confirmOrder', // 动态路由传参
    name: '确认订单',
    component: () => import('@views/ConfirmOrder'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search', // 动态路由传参
    name: '搜索页',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResult', // 动态路由传参
    name: '搜索结果页',
    component: () => import('@views/SearchResult'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由的前置守卫
router.beforeEach((to, from, next) => {
  // 判断
  if (to.meta.needLogin) {
    if (isLogin()) {
      // 登陆了
      next()
    } else { // 没有登录
      next({
        path: '/login',
        query: {
          from: to.path // to 里面有一个path，是跳转过来的页面
        }
      })
    }
  } else {
    next()
  }
})
export default router
